import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpService } from '../service/http.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { uuid } from '@tinymce/tinymce-angular/utils/Utils';
import { NzNotificationService } from 'ng-zorro-antd/notification';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent {
  isCollapsed = false;

  public timer: any;
  public isAdministrator = false;
  public userName = '';
  public userDetails: any = {};

  constructor(
    private router: Router,
    private httpService: HttpService,
    private modalService: NzMessageService,
    private notification: NzNotificationService,
  ) {}

  ngOnInit(): void {
    const user = localStorage.getItem('user');
    if (user != null) {
      this.userDetails = JSON.parse(user);
    } else {
      this.router.navigate(['/login']);
    }
    const userType = this.userDetails.userType;
    if ('administrators' == userType) {
      this.isAdministrator = true;
    }
    const session = this.userDetails.session;
    if (session == null) {
      this.router.navigate(['/login']);
    }
    this.checkSession();
    const uu = Math.random();
    this.timer = setInterval(() => {
      this.checkSession();
    }, 30000);
  }

  checkSession() {
    const user = localStorage.getItem('user');
    if (user != null) {
      this.userDetails = JSON.parse(user);
    } else {
      this.router.navigate(['/login']);
    }
    const url = '/rest/session/renew';
    const data = {
      session: this.userDetails.session,
      id: this.userDetails.id,
    };
    return this.httpService.post(url, data).subscribe((res: any) => {
      if (res.code != '0000') {
        this.router.navigate(['/login']);
      } else {
      }
    });
  }

  logout() {
    const user = localStorage.getItem('user');
    if (user != null) {
      this.userDetails = JSON.parse(user);
    } else {
      this.router.navigate(['/login']);
    }
    const url = '/rest/logout';
    const session = this.userDetails.session;
    const data = {
      session: session,
      id: this.userDetails.id,
    };
    localStorage.clear();
    clearInterval(this.timer);
    this.timer = null;
    localStorage.removeItem('user');
    this.userDetails = {};
    console.log('check if session is deleted');
    this.router.navigate(['/login']);
  }
}
